﻿/*
 * QWine Queue Machine (Special build for Immigration Office)
 * Copyright (C) 2010 Wish Enterprise Development Team

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact Us:
 * E-Mail   : contact@wishenterprise.com
 * 
 * */

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Origami.Security;

namespace QWRepository
{
    /// <summary>
    /// XmlConfiguration
    /// </summary>
    public class XmlConfiguration : IDisposable
    {
        private DBLogonInfo _dbLogonInfo;
        private Boolean _disposedValue;

        /// <summary>
        /// Constructor #1
        /// </summary>
        /// <param name="dbLogonInfo">DBLogonInfo</param>
        public XmlConfiguration(
            DBLogonInfo dbLogonInfo)
        {
            _dbLogonInfo = dbLogonInfo;
        }

        /// <summary>
        /// Get or Set DBLogonInfo
        /// </summary>
        public DBLogonInfo DBLogonInfo
        {
            get { return _dbLogonInfo; }
            set { _dbLogonInfo = value; }
        }

        #region IDisposable Members

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        /// <summary>
        /// Dispose
        /// </summary>
        /// <param name="disposing">bool</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue && disposing)
            {
            }
            _disposedValue = true;
        }

        /// <summary>
        /// Writes this instance.
        /// </summary>
        /// <returns></returns>
        public bool Write()
        {
            bool retVal = false;
            string fileName = GetConfigurationFile();

            try
            {
                // --- Write to XML
                using (var writer =
                    new XmlTextWriter(fileName,
                                      Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartDocument(false);
                    writer.WriteStartElement("SmsElement", null);
                    writer.WriteElementString("Provider", null,
                                                       Encrypt(_dbLogonInfo.Provider));
                    writer.WriteElementString("ConnectionString", null,
                                                       Encrypt(_dbLogonInfo.ConnectionString));
                    writer.WriteEndElement();
                    writer.Flush();
                    writer.Close();
                    retVal = true;
                }
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message,
                                @"Error!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            return retVal;
        }

        /// <summary>
        /// Encrypts the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        private string Encrypt(string input)
        {
            var crypto =
                new SymmetricCryptography(SymmetricProvider.TripleDES)
                    {
                        Key =
                            _dbLogonInfo.ApplicationId.
                                ToLower() +
                            Definition.CONFIGURATION_KEY,
                        Salt = Definition.CONFIGURATION_SALT
                    };
            return crypto.Encrypt(input);
        }

        /// <summary>
        /// Decrypts the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        private string Decrypt(string input)
        {
            var crypto =
                new SymmetricCryptography(SymmetricProvider.TripleDES)
                    {
                        Key =
                            _dbLogonInfo.ApplicationId.
                                ToLower() +
                            Definition.CONFIGURATION_KEY,
                        Salt = Definition.CONFIGURATION_SALT
                    };
            return crypto.Decrypt(input);
        }

        /// <summary>
        /// Gets the configuration file.
        /// </summary>
        /// <returns></returns>
        private string GetConfigurationFile()
        {
            return string.Format("{0}/{1}.xml", 
                Application.StartupPath, _dbLogonInfo.ApplicationId.ToLower());
        }

        /// <summary>
        /// Read Configuration
        /// </summary>
        /// <returns>bool</returns>
        public bool Read()
        {
            bool retVal = false;
            string fileName = GetConfigurationFile();

            // --- If file not exist
            if (!File.Exists(fileName)) return false;

            try
            {
                var xml = new DataSet();
                xml.ReadXml(fileName);

                // --- Get each column
                var linq =
                    from r in xml.Tables[0].AsEnumerable()
                    select new
                               {
                                   Provider = Decrypt(r.Field<string>("Provider")),
                                   ConnectionString = Decrypt(r.Field<string>("ConnectionString"))
                               };

                foreach (var r in linq)
                {
                    _dbLogonInfo.Provider = r.Provider;
                    _dbLogonInfo.ConnectionString = r.ConnectionString;
                }

                retVal = true;
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message,
                                @"Error!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }

            return retVal;
        }

        /// <summary>
        /// Removes this instance.
        /// </summary>
        /// <returns></returns>
        public bool Remove()
        {
            bool retVal = false;
            try
            {
                string fileName = GetConfigurationFile();
                if (File.Exists(fileName))
                {
                    File.SetAttributes(fileName,
                                       FileAttributes.Temporary); // Set as temporary
                    File.Delete(fileName); // Remove File
                }
                retVal = true;
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message,
                                @"Error!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            return retVal;
        }
    }
}